package com.tc.vms.message;

import com.tc.vms.exception.VmsClientException;
import com.tc.vms.utils.Utils;

import java.net.InetSocketAddress;

/**
 * Created by yonghua.zhang on 2015/12/15.
 */
public final class MessageIdGenerator {
    private InetSocketAddress socketAddress;
    private int pId;

    public MessageIdGenerator(InetSocketAddress socketAddress) {
        this.socketAddress = socketAddress;
        this.pId = Utils.getPid();
    }

    public MessageIdGenerator() {
        int randomPort = Math.abs(Utils.randomInt(Short.MAX_VALUE));
        this.pId = Utils.getPid();
        try {
            socketAddress = new InetSocketAddress(Utils.getLocalAddress(), randomPort);
        } catch (Exception e) {
        }
        if (socketAddress == null || socketAddress.isUnresolved()) {
            socketAddress = new InetSocketAddress("127.0.0.1", randomPort);
        }
    }

    public MessageId genMessageId() {
        return new MessageId(socketAddress, pId);
    }

    public MessageId parseMessageId(String mesgIdStr) throws VmsClientException {
        return MessageId.decode(mesgIdStr);
    }
}
